//
//  WBRefreshControl.swift
//  weibo
//
//  Created by yellow on 15/10/24.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit

/// 刷新视图偏移量
let WBRefreshViewOffset:CGFloat = -60


/// 自定义下拉刷新控件(可支持代码和xib)
class WBRefreshControl: UIRefreshControl {
    
    //beginRefreshing() 只会开启刷新控件的动作，但是不会主动触发监听方法
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startLoadingAnimation()
    }
    
    //结束刷新动画
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.endLoadingAnimation()
    }

    
    //代码构造函数
    override init() {
        super.init()
        setUI()
    }

    //这是xib构造函数
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUI()
    }
    
    private func setUI(){
        //添加自定义视图
        addSubview(refreshView)
        refreshView.tintColor = UIColor.clearColor()
        //自动布局,从xib加载的view是没有大小，需要设置大小的约束
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        //使用KVO监听刷新view的位置，当达到临界值就可以执行更新了
        
        //1.注册KVO
        self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
    }
    
    deinit{
        //2.注销KVO
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    //懒加载控件，UIRefreshControl默认是有一个刷新控件视图的，我们的自定义视图只能覆盖到上面
    private lazy var refreshView:WBRefreshView = WBRefreshView.refreshView()
    
    
    //KVO的位置监听事件
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //上拉得直接过滤掉
        guard  frame.origin.y < 0 else{
            return
        }
        
        //当进入刷新状态时，隐藏最上层的tipView，播放转圈动画
        if refreshing {
            refreshView.startLoadingAnimation()
            return
        }
        
        let currentY = frame.origin.y
        if currentY < WBRefreshViewOffset && refreshView.reloadFlag == false {
            refreshView.reloadFlag = true
        }else if currentY > WBRefreshViewOffset && refreshView.reloadFlag == true{
            refreshView.reloadFlag = false
        }
    }
}

//下拉刷新视图
class WBRefreshView:UIView {
    
    
    //刷新视图标致
    var reloadFlag = false {
        didSet{
            var angle = CGFloat(M_PI)
//            angle += reloadFlag ? -0.01 : 0.01
            
            /*
             iOS旋转动画中，旋转方向是就近原则。
             因为默认箭头是向下的，为了达到向上是为顺时针，向下为逆时针。
             需要设置向下的弧度比一个半圆弧度小就可以达到逆时针旋转了。
             而向上设置+0.01是为了达到一个平和+-
            */
            if reloadFlag == false {
                angle += 0.01
            }else{
                angle += -0.01
            }
            UIView .animateWithDuration(0.5) { () -> Void in
                self.arrowIcon.transform = CGAffineTransformRotate(self.arrowIcon.transform,angle)
            }
        }
    }
    
    
    //箭头图标
    @IBOutlet weak var arrowIcon: UIImageView!
    //加载转圈图标
    @IBOutlet weak var loadingIcon: UIImageView!
    
    //提示视图(带有箭头的)
    @IBOutlet weak var tipView: UIView!
    /// 类方法创建xib视图
    ///
    /// - returns: 下拉刷新视图
    class func refreshView()->(WBRefreshView) {
        //加载xib，bundle为nil，系统会从mainbundle中searcher
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil).last as! WBRefreshView
    }
    
    //开始播放加载转圈动画
    private func startLoadingAnimation(){
        self.tipView.hidden = true
        
        
        //创建基本动画
        let keyAnima = "transform.rotation"
        //当在执行动画时，就不重复执行动画了
        if self.loadingIcon.layer.animationForKey(keyAnima) != nil{
            return
        }
        let baseAnimation = CABasicAnimation(keyPath: keyAnima)
        baseAnimation.toValue = 2 * M_PI
        baseAnimation.duration = 2
        baseAnimation.repeatCount = MAXFLOAT
        //防止动画，在app进入后台会结束动画
        baseAnimation.removedOnCompletion = false
        //将动画添加到加载转圈图标上
        self.loadingIcon.layer.addAnimation(baseAnimation, forKey: keyAnima)
    }
    
    //结束播放加载转圈动画
    private func endLoadingAnimation(){
        self.tipView.hidden = false
        self.arrowIcon.layer.removeAllAnimations()
    }
}
